import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhongJinTao
 * Date: 2024-03-12
 * Time: 23:00
 */

public class UdpEchoServer2 {
    DatagramSocket socket = null;

    public UdpEchoServer2(int serverPort) throws SocketException {
        socket = new DatagramSocket(serverPort);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            //1、接受请求并解析请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            //把接受到的数据报里的字节数组转换成字符串
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            //2、根据解析计算响应
            String response = process(request);
            //3、把响应发送给客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    response.getBytes().length, requestPacket.getSocketAddress());
            socket.send(responsePacket);
            //打印日志
            System.out.printf("[%s : %d] req: %s resp: %s", requestPacket.getAddress(),
                    requestPacket.getPort(), request, response);
            System.out.println();
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        udpEchoServer.start();
    }
}

